import { Component, Fragment } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { UploadEditor } from "api/common.js";

class EditorCom extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  // 输入触发的方法-拿到value
  handleEditorChange = value => {
    this.triggerChange(value);
  };
  // 返回数据--到from.item
  triggerChange = changedValue => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };
  render() {
    // 更多配置 见官网 http://tinymce.ax-z.cn/  这个富文本要收费但是功能够多
    const editorObj = {
      height: "800px",
      language: "zh_CN",
      plugins: "table lists link image preview code",
      toolbar: `formatselect | code | preview | bold italic strikethrough forecolor backcolor | 
      link image | alignleft aligncenter alignright alignjustify  | 
      numlist bullist outdent indent`,
      relative_urls: false,
      file_picker_types: "image",
      images_upload_url: "http",
      image_advtab: true,
      image_uploadtab: true,
      images_upload_handler: (blobInfo, success, failure) => {
        // 这里是上传图片 文字一样
        var formData;
        var file = blobInfo.blob(); //转化为易于理解的file对象
        formData = new FormData();
        formData.append("file", file, file.name); //此处与源文档不一样---第一个file指的是name的名字为file <form><input type='file' name='file'></form>
        UploadEditor(formData) //根据自己情况来配置--接口
          .then(response => {
            const url = response.data.url;
            // console.log(url);
            success(url);
          })
          .catch(error => {
            failure(error);
            // console.log(error)
          });
      }
    };

    return (
      <Fragment>
        <Editor
          inline={false}
          selector="editorStateRef" // 选择器
          apiKey="官网上申请的key值"
          initialValue={""} //默认值
          init={{ ...editorObj }} //配置
          onEditorChange={this.handleEditorChange} //每次输入获取的值
        />
      </Fragment>
    );
  }
}

export default EditorCom;
